package com.zyx.concurrentdemo.mytest.c05;

import com.zyx.concurrentdemo.c02basic.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zyx
 * @since 2021/10/17 08:40
 * desc: 利用 volatile进行连接段结束
 */
@Slf4j(topic = "c.TwoPhaseTerminateDemo")
public class TwoPhaseTerminateDemo {

    public static void main(String[] args) {
        Monitor monitor = new Monitor();
        monitor.start();
        Sleeper.sleep(3.5);
        monitor.stop();
    }

}

@Slf4j(topic = "c.Monitor")
class Monitor {

    static Thread monitor;

    private volatile boolean isStopped = false;

    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                // 如果标志为停止, 则结束运行
                if (isStopped) {
                    log.debug("处理后事...");
                    break;
                }
                log.debug("执行监控");
                // 标志为运行, 则睡1s, 被打断时退出
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.warn("被打断了,处理后事...");
                }
            }
        });
        monitor.start();
    }

    public void stop() {
        this.isStopped = true;
        monitor.interrupt();
    }

}